package com.zerox.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zerox.domain.TableVo;
import com.zerox.pojo.User;
import com.zerox.service.UserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import javax.validation.Valid;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping(value = "/list", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String list(Model model, Integer page, Integer limit, String realName, Integer roleId) {
        List<User> list = userService.list(page, limit, realName, roleId);
        int count = userService.count(realName, roleId);
        TableVo tableVo = new TableVo(0, count, list, "");
        String json = JSON.toJSONString(tableVo);
        return json;
    }

    @GetMapping("/list2")
    public String list2() {
        return "list";
    }

    @GetMapping("/show")
    public String view( int id, Model model, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        User show = userService.show(id);
        String s = JSONObject.toJSONString(show);
        writer.print(s);
//        model.addAttribute("show", show);
        return null;
    }
    @GetMapping("view{id}")
    public String show(@PathVariable int id, Model model) {
        User show = userService.show(id);
        model.addAttribute("show", show);
        return "view";
    }
    @GetMapping("/delete{id}")
    @ResponseBody
    public String delete(@PathVariable int id, Model model) {
        int delete = userService.delete(id);
        return delete > 0 ? "true" : "false";
    }

    @GetMapping("/add1")
    public String add1() {
        return "add";
    }

    @PostMapping("/add")
    public String add(Model model,@Valid User user, BindingResult bindingResult, MultipartFile pic, HttpServletRequest request) throws IOException, FileUploadException {
//        DiskFileItemFactory factroy = new DiskFileItemFactory();
//        //创建文件上传解析器
//        ServletFileUpload upload = new ServletFileUpload(factroy);

//        List<FileItem> fileItems = upload.parseRequest(request);
//        for (FileItem fileItem:fileItems){
//            System.out.println(fileItem.getString());
//        }

        if (bindingResult.hasErrors()) {
            //获取到所有的错误
            List<FieldError> fieldError = bindingResult.getFieldErrors();
            for (FieldError fi : fieldError) {
                model.addAttribute(fi.getField() + "Error", fi.getDefaultMessage());
            }
            return "add";
        }
        if (pic!=null){
            if (pic.getSize()>5000000){
                model.addAttribute("文件超过5M不能上传");
                return "add";
            }
        }

        //自己自定名字
        String substring = pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf("."));

        if (".jpg.png".indexOf(substring)==-1){
            model.addAttribute("文件格式不正确，不能上传");
            return "add";
        }
        //指定文件储蓄的目录
        String statics = request.getSession().getServletContext().getRealPath("statics") + File.separator + "upload";
        String s = RandomUtils.nextInt(1000000) + "_pic" + substring;
        File file = new File(statics+File.separator+s);
        //如果文件不存在，就创建
        if (!file.exists()){
            file.mkdirs();
        }
        //将文件储蓄到指定位置
        pic.transferTo(file);
        user.setIdpicpath(s);
        int add = userService.add(user);
        if (add > 0) {
            return "redirect:list2";
        }
        model.addAttribute("errorMsg", "添加失败");
        return "add";
    }

    @GetMapping("/update{id}")
    public String update(@PathVariable int id, Model model) {
        User show = userService.show(id);
        model.addAttribute("show", show);
        return "update";
    }

    @PostMapping("/update2")
    public String update2(@Valid User user, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            //获取到所有的错误
            List<FieldError> fieldError = bindingResult.getFieldErrors();
            for (FieldError fi : fieldError) {
                model.addAttribute(fi.getField() + "Error", fi.getDefaultMessage());
            }
            return "update";
        }
        int add = userService.update(user);
        if (add > 0) {
            return "redirect:list2";
        }
        model.addAttribute("errorMsg", "修改失败");
        return "add";
    }
}
